
using System.Collections.Generic;
using System.Web;
using com.byt.webcore.utils;
using System.IO;
using System.Data.Common;
using System;

namespace com.byt.webcore.config
{

    public class AppProperties : IConfig
    {

        private string serverPath = null;
        private static string CONFIGURATION_FILE = "app.txt";
        private static Dictionary<string, string> propiedades;

        public AppProperties(HttpRequest request)
            : base(request)
        {
            getServerPath(request);
        }

        public override string getServerPath(HttpRequest request)
        {
            if (string.IsNullOrEmpty(serverPath))
            {
                serverPath = request.PhysicalApplicationPath;

                /*
                 string host = (request.Url.IsDefaultPort) ? request.Url.Host : request.Url.Authority;
                host = string.Format("{0}://{1}", request.Url.Scheme, host);
                if (HttpContext.Current.Request.ApplicationPath == "/")
                    host = host;
                else
                    host = host + HttpContext.Current.Request.ApplicationPath;

                host = host + "/desktop?c=GETSERVERPATH";


                 string host = "http://" + request.getServerName() + ":" + request.getServerPort() + "/byt/desktop?c=GETSERVERPATH";

                   try {
                       // establecemos conexion
                       URL url = new URL(host);
                       URLConnection urlCon = url.openConnection();
                       urlCon.connect();
                       Thread.sleep(100);
                
                       while(urlCon.getContentLength() < 1){
                           Thread.sleep(10);
                       }

                       // Se obtiene el inputStream
                       InputStream is = urlCon.getInputStream();
                       InputStreamReader sr = new InputStreamReader(is);

                       // Lectura de la cadena de salida
                       StringBuilder sb = new StringBuilder();
                       char[] array = new char[1000]; // buffer temporal de lectura.
                       int leido = sr.read(array);
                       while (leido > 0) {
                           sb.append(array, 0, leido);
                           leido = sr.read(array);
                       }
                       // cierre de conexion y fichero.
                       is.close();
                       sr.close();
                       serverPath = sb.ToString();

                   } catch (Exception e) {
                       throw new Exception("Error al leer \"ServerPath\" de " + host, e);
                   }
                * */

            }
            return serverPath;
        }

        public override string getServerShared(ServletBase.Parameters p)
        {
            return Path.Combine(getServerPath(p), "shared");
        }

        private Dictionary<string, string> getProperties(ServletBase.Parameters p)
        {
            if (AppProperties.propiedades == null)
            {
                
                string fi = "";
                if (p == null)
                    fi = Path.Combine(getServerPath(HttpContext.Current.Request), CONFIGURATION_FILE);
                else
                    fi = Path.Combine(getServerPath(p.req), CONFIGURATION_FILE);

                AppProperties.propiedades = new Dictionary<string, string>();
                string line, key, value;
                int pos;
                StreamReader reader = new StreamReader(fi);
                try
                {
                    do
                    {
                        line = reader.ReadLine().Trim();
                        pos = line.IndexOf("=");
                        if (!string.IsNullOrEmpty(line) && line[0] != '#' && pos > -1)
                        {
                            key = line.Substring(0, pos).Trim();
                            value = line.Substring(pos + 1).Trim();
                            AppProperties.propiedades.Add(key, value);
                        }
                    } while (reader.Peek() != -1);
                }
                catch { }
                finally { reader.Close(); }
            }
            return AppProperties.propiedades;
        }

        private string getProperty(ServletBase.Parameters p, string key, string keyDefault)
        {
            string value;
            Dictionary<string, string> prop = getProperties(p);
            key = key.ToLower();
            try
            {
                value = prop[key];
                if (string.IsNullOrEmpty(value))
                    value = prop[keyDefault];
            }
            catch
            {
                value = prop[keyDefault];
            }
            return value;
        }

        public override DbConnection getConnection(ServletBase.Parameters p, string nombre)
        {
            /*
            // Obtener el nombre completo del ensamblado
            string nameAssembly = typeof(System.Data.SqlClient.SqlConnection).AssemblyQualifiedName;
            nameAssembly = "";
            */
             
            string driver = getProperty(p, "connection." + nombre + ".driver", "connection.default.driver");
            string url = getProperty(p, "connection." + nombre + ".url", "connection.default.url");

            Type typeConn = Type.GetType(driver);

            DbConnection conn = (DbConnection)Activator.CreateInstance(typeConn, new object[] { url });
            conn.Open();


            //
            //System.Data.SqlClient.SqlConnection v = new System.Data.SqlClient.SqlConnection();

            //

            return conn;

        }

        public override string getPath(ServletBase.Parameters p, string pathName)
        {
            string s = getProperties(p)["path." + pathName];
            return s;
        }

        public override string getEntry(ServletBase.Parameters p, string entryName)
        {
            string s = getProperties(p)[entryName];
            return s;
        }

    }
}